<?php

namespace app\admin\controller\vppz;

use app\admin\model\vppz\App;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class VipPackage extends Base
{

    /**
     * Service模型对象
     * @var \app\admin\model\vppz\Qxzl
     */
    protected $model = null;

	protected $searchFields = ['id','title'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\VipPackage;
        $this->channelModel = new \app\admin\model\vppz\VipChannel;
    }

public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->with(['vip_channel'])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $k=>$row) {
                $row->getRelation('vip_channel')->visible(['value']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    protected function filter(&$query)
    {
        // 添加性别筛选条件
        if ($this->request->has('hospital_name')) {
            $hospital_name = $this->request->param('hospital_name');
            if ($hospital_name !== '') {
                $query->where('hospital.name','like', '%'.$hospital_name.'%');
            }
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
/**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $result = false;
            try {
                $form['originalPrice'] = max($form['originalPrice'],1);
                $data = array(
                    'title'=>$form['title'],
                    'duration'=>$form['duration'],
                    'price'=>$form['price'],
                    'is_show'=>$form['is_show'],
                    'channel'=>$form['channel'],
                    'content'=>json_encode($form['content']),
                    'originalPrice'=>$form['originalPrice'],
                    'discount'=>sprintf("%.2f",$form['price'] * 100/$form['originalPrice']),
                );
                $res = $this->model->save($data);
                if($res) {
                    $this->success();
                }else{
                    $this->error('添加失败');
                }
            } catch (ValidateException|PDOException|Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $channel = $this->channelModel->select();
        $this->view->assign('channels',$channel);
        $AppModel = new App;
		$app = $AppModel->find(1);
        $benefitsList = json_decode($app['family_benefits'],true);
        $res = [];
        if(empty($benefitsList) === FALSE){
            foreach ($benefitsList as $k=>$v){
                array_push($res,array(
                    'id'=>$k,
                    'title'=>$v
                ));
            }
        }
        $this->view->assign('benefitsList',$res);
        return parent::add();
    }
/**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
        $channel = $this->channelModel->select();
        $this->view->assign('channels',$channel);
        $row['content'] = json_decode($row['content'],true);
        $this->view->assign('row', $row);
        $AppModel = new App;
		$app = $AppModel->find(1);
        $benefitsList = json_decode($app['family_benefits'],true);
        $res = [];
        if(empty($benefitsList) === FALSE){
            foreach ($benefitsList as $k=>$v){
                array_push($res,array(
                    'id'=>$k,
                    'title'=>$v
                ));
            }
        }
        $this->view->assign('benefitsList',$res);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        try {
            $data = array(
                    'title'=>$form['title'],
                    'duration'=>$form['duration'],
                    'price'=>$form['price'],
                    'originalPrice'=>$form['originalPrice'],
                    'is_show'=>$form['is_show'],
                    'channel'=>$form['channel'],
                    'content'=>json_encode($form['content']),
                    'updatetime'=>time(),
                    'discount'=>sprintf("%.2f",$form['price'] * 100/$form['originalPrice']),
                );
                $res = $this->model->save($data,['id'=>$ids]);
                if($res) {
                    $this->success();
                }else{
                    $this->error('编辑失败');
                }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }
}
